package com.situ.shoplookweb.service.impl;

import com.situ.shoplook.common.mapper.GoodsInfoMapper;
import com.situ.shoplook.common.mapper.ShoppingCartMapper;
import com.situ.shoplook.common.model.ShoppingCart;
import com.situ.shoplook.common.model.User;
import com.situ.shoplook.common.service.GoodsInfoService;
import com.situ.shoplookweb.service.ShoppingCartService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author xinchen
 * @Date: 2024/09/05/ 16:48
 * @Description
 */
@Service
public class shoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private GoodsInfoMapper goodsInfoMapper;

    @Override
    public List<ShoppingCart> getMyShoppingCartItems(Long userId) {
        List<ShoppingCart> myShoppingCartItems = shoppingCartMapper.getMyShoppingCartItems(userId);
        myShoppingCartItems.stream().forEach(item -> item.setGoodsInfo(this.goodsInfoMapper.selectByPrimaryKey(item.getGoodsId())));
        return myShoppingCartItems;
    }

    @Override
    public int addShoppingCart(ShoppingCart shoppingCart, HttpSession session) {
        /**
         * 添加到购物车中,如果商品相同，则数量加一
         */
        User user = (User) session.getAttribute("newBeeMallUser");
        /**
         * 获取使用的购物车
         */
        List<ShoppingCart> myShoppingCartItems = this.getMyShoppingCartItems(user.getUserId());
        for (ShoppingCart item : myShoppingCartItems) {
            if (item.getGoodsId().equals(shoppingCart.getGoodsId())) {
                item.setGoodsCount(item.getGoodsCount() + 1);
                return this.updateShoppingCart(item, session);
            }
        }
        return shoppingCartMapper.insertSelective(shoppingCart);
    }

    @Override
    public int updateShoppingCart(ShoppingCart shoppingCart,HttpSession session) {
        int count = shoppingCartMapper.updateByPrimaryKeySelective(shoppingCart);
        if(count > 0){
            /**
             * 清楚购物车
             */
            User user = (User) session.getAttribute("newBeeMallUser");
            int co = this.shoppingCartMapper.findByUserIdCount(user.getUserId());
            session.setAttribute("shopCartItemCount",co);
        }
        return count;
    }

    @Override
    public int deleteShoppingCart(Long cartId,HttpSession session) {
        int count = shoppingCartMapper.deleteByPrimaryKey(cartId);
        if(count > 0){
            /**
             * 清楚购物车
             */
            User user = (User) session.getAttribute("newBeeMallUser");
            int co = this.shoppingCartMapper.findByUserIdCount(user.getUserId());
            session.setAttribute("shopCartItemCount",co);
        }
        return count;
    }
}
